unit fmMain;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, DB, Grids, DBGrids, ComCtrls;

type
  TForm1 = class(TForm)
    Panel1: TPanel;
    btnGetData: TButton;
    pc1: TPageControl;
    tsLog: TTabSheet;
    Memo1: TMemo;
    dc1: TDataSource;
    edtServerHost: TEdit;
    edtServerPort: TEdit;
    edtFileName: TEdit;
    tsStatement: TTabSheet;
    mSQL: TMemo;
    procedure btnGetDataClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  slSQL;

function DeleteLastSemicolon(AStr: string): string;
var
  LastChar: string;
  i, Len: Integer;
begin
  Len := Length(AStr);
  LastChar := Copy(AStr, Len, 1);
  if LastChar = ';' then
    Delete(AStr, Len, 1);
  Result := AStr;  
end;

procedure TForm1.btnGetDataClick(Sender: TObject);
var
//  OutData: string;
  SQL, RowStr: string;
  Res, ColumnCount, RecCount: Integer;
  slCSV: TStringList;
  i: Integer;
begin
  Memo1.Clear;
  Memo1.Lines.Add('Results of: ');

//  SetLength(OutData, BUFFER_LENGTH);
//  Res := slConnect(edtServerHost.Text, StrToInt(edtServerPort.Text), 'E0', OutData);
//  Memo1.Lines.Add('sluConnect -> Result: ' + IntToStr(Res) + ' OutData: ' + OutData);
  Res := slConnect(edtServerHost.Text, StrToInt(edtServerPort.Text), 'E0');
  Memo1.Lines.Add('sluConnect -> Result: ' + IntToStr(Res));
  Memo1.Lines.Add('slGetError -> Error: ' + slGetError());

  Res := slOpen(edtFileName.Text, 'C');
  Memo1.Lines.Add('sluOpen -> Result: ' + IntToStr(Res));
  Memo1.Lines.Add('slGetError -> Error: ' + slGetError());

  SQL := mSQL.Text;
  Res := slSel(SQL);
  Memo1.Lines.Add('sluSel -> Result: ' + IntToStr(Res));
  Memo1.Lines.Add('slGetError -> Error: ' + slGetError());

  slCSV := TStringList.Create;
  Memo1.Lines.Add(#13#10'Print data:'#13#10);
  RecCount := 0;
  RowStr := '';
  ColumnCount := slGetColumnCount();
  for i := 1 to ColumnCount do begin
    RowStr := RowStr + '"' + slGetColumnName(i) + '";';
  end;
  RowStr := DeleteLastSemicolon(RowStr);
  slCSV.Add(RowStr);
  Memo1.Lines.Add(Format('%5d'#9,[RecCount]) + RowStr);
  while slGetRow() <> 0 do begin
    Inc(RecCount);
    RowStr := '';
    for i := 1 to ColumnCount do begin
      RowStr := RowStr + '"' + slF(i) + '";';
    end;
    RowStr := DeleteLastSemicolon(RowStr);
    slCSV.Add(RowStr);
    Memo1.Lines.Add(Format('%5d'#9,[RecCount]) + RowStr);
    Application.ProcessMessages;
  end;
  slClose();
  slDisconnect();
  Memo1.Lines.Add('sluGetRow: Count: ' + IntToStr(RecCount));

  slCSV.SaveToFile('test.csv');
  FreeAndNil(slCSV);
end;

end.
